<?php
include_once('inc/functions.inc.php');

if(!isEmpty(getParam('operation'))){
    
    switch(getParam('operation')){
        case 'cuentas': {
            fntConciliacionGetCuentas($db);
            break;
        }
        case 'conciliaciones': {
            fntConciliacionGetConciliaciones($db);
            break;
        }
        case 'contenido': {
            fntConciliacionGetContenido($db);
            break;
        }
        case 'actual': {
            fntConciliacionActual($db);
            break;
        }
        case 's': {
            fntConciliacionGuardar($db);
            break;
        }
        case 'c': {
            fntConciliacionCerrar($db);
            break;
        }        
    }
    die();
}

function fntConciliacionGetCuentas( $db ) {
    
    $empresa = getParam("empresa");
    
    $strQuery = "SELECT * FROM cllg_bnc_cuenta WHERE ESTADO = '1' AND FK_EMPRESA = '{$empresa}' ORDER BY NUMERO";
    $qTMP = $db->query($strQuery);
    $intNumRows = $db->num_rows;

    $arrCuentas = array();
    if( $intNumRows > 0 ) {
        while ( $rTMP = $db->fetch_array($qTMP) ) { 
            $arrCuentas[$rTMP["NUMERO"]] = $rTMP["CUENTA"];       
        }
    }
    $db->free_result($qTMP);
    
    ?>
        <b>Seleccione cuenta:</b>
        <select name="sltConciliacionCuenta">
        <?php
        reset($arrCuentas);
        while( $arrTMP = each($arrCuentas) ) {
            
            ?>
            <option value="<?php print $arrTMP["key"]; ?>"><?php print $arrTMP["value"]; ?></option>
            <?php
            
        } 
        ?>
        </select>
        <script type="text/javascript" language="javascript">
        $("select[name='sltConciliacionCuenta']").change( function() {
            fntConciliacionGetConciliaciones();
        });
        </script>
    <?php    
    
}
function fntConciliacionGetConciliaciones( $db ) {
    
    $cuenta = getParam("cuenta");
    $conciliacion = getParam("conciliacion");
    
    $strQuery = "SELECT ID, FK_CUENTA, DATE_FORMAT(FECHA, '%d-%m-%Y') AS FECHAS 
                 FROM   cllg_bnc_conciliacion WHERE FK_CUENTA = '{$cuenta}' ORDER BY FECHA";
    $qTMP = $db->query($strQuery);
    $intNumRows = $db->num_rows;

    if( $intNumRows > 0 ) {
        
        ?>
        <b>Seleccione conciliación:</b>
        <select name="sltConciliacionConciliacion">
        <option value="0">--- Ingresar nueva ---</option>
        <?php
        while ( $rTMP = $db->fetch_array($qTMP) ) {
            ?>
            <option value="<?php print $rTMP["ID"]; ?>" <?php print ($conciliacion == $rTMP["ID"])? "selected" : ""; ?>><?php print $rTMP["ID"]; ?> - <?php print $rTMP["FECHAS"]; ?></option>
            <?php
        }
        ?>
        </select>
        <?php
        
    }
    else {
        
        ?>
        <b>Seleccione conciliación:</b>
        <select name="sltConciliacionConciliacion">
            <option value="0">--- Ingresar nueva ---</option>
        </select>
        <?php
    
    }
    $db->free_result($qTMP);
    ?>
    <script type="text/javascript" language="javascript">
    $("select[name='sltConciliacionConciliacion']").change( function() {
        fntConciliacionGetContenido();
    });
    </script>
    <?php
    
}
function fntConciliacionGetContenido( $db ) {
    
    $ID = getParam("conciliacion");
    $arrConciliacion = array();
    if( $ID > 0 ) { 
        $strQuery = "SELECT ID, FK_CUENTA, MONTH(FECHA) AS MES, YEAR(FECHA) AS ANIO, SALDO_I, SALDO_F, ESTADO 
                     FROM   cllg_bnc_conciliacion WHERE ID = '{$ID}'";
        $qTMP = $db->query($strQuery);
        while ( $rTMP = $db->fetch_array($qTMP) ) {
            $arrConciliacion = $rTMP;
        }
        $db->free_result($qTMP);
    }
    else {
        $strQuery = "SELECT MAX(ID) AS ID, MONTH(NOW()) AS MES, YEAR(NOW()) AS ANIO, '0' AS SALDO_I, '0' AS SALDO_F, '1' AS ESTADO  
                     FROM   cllg_bnc_conciliacion";
        $qTMP = $db->query($strQuery);
        while ( $rTMP = $db->fetch_array($qTMP) ) {
            $rTMP["ID"] = $rTMP["ID"] + 1;
            $arrConciliacion = $rTMP;
        }
        $db->free_result($qTMP);        
    }
    date_default_timezone_set("America/Guatemala");
    $strAnio = date("Y");
    ?>

    <div style="width: 100%; height: 30px; float: left;">&nbsp;</div>
    <div style="width: 100%; height: 30px; float: left;"><b>Conciliación Bancaria No. <?php print $arrConciliacion["ID"]; ?></b></div>
    <div style="width: 16%; height: 30px; float: left;"><b>Mes a conciliar:</b></div>
    <div style="width: 84%; height: 30px; float: left;">
        <select name="sltConciliacionMes">
            <option value="1" <?php print ($arrConciliacion["MES"] == 1) ? "selected" : ""; ?>>Enero</option>
            <option value="2" <?php print ($arrConciliacion["MES"] == 2) ? "selected" : ""; ?>>Febrero</option>
            <option value="3" <?php print ($arrConciliacion["MES"] == 3) ? "selected" : ""; ?>>Marzo</option>
            <option value="4" <?php print ($arrConciliacion["MES"] == 4) ? "selected" : ""; ?>>Abril</option>
            <option value="5" <?php print ($arrConciliacion["MES"] == 5) ? "selected" : ""; ?>>Mayo</option>
            <option value="6" <?php print ($arrConciliacion["MES"] == 6) ? "selected" : ""; ?>>Junio</option>
            <option value="7" <?php print ($arrConciliacion["MES"] == 7) ? "selected" : ""; ?>>Julio</option>
            <option value="8" <?php print ($arrConciliacion["MES"] == 8) ? "selected" : ""; ?>>Agosto</option>
            <option value="9" <?php print ($arrConciliacion["MES"] == 9) ? "selected" : ""; ?>>Septiembre</option>
            <option value="10" <?php print ($arrConciliacion["MES"] == 10) ? "selected" : ""; ?>>Octubre</option>
            <option value="11" <?php print ($arrConciliacion["MES"] == 11) ? "selected" : ""; ?>>Noviembre</option>
            <option value="12" <?php print ($arrConciliacion["MES"] == 12) ? "selected" : ""; ?>>Diciembre</option>
        </select>
        <select name="sltConciliacionAnio">
            <?php
            for($i=$strAnio-10; $i<=$strAnio; $i++ ) {
                ?>
                <option value="<?php print $i; ?>" <?php print ($arrConciliacion["ANIO"] == $i) ? "selected" : ""; ?>><?php print $i; ?></option>
                <?php
            }
            ?>
            
        </select>
    </div>
    <div style="width: 16%; height: 30px; float: left;"><b>Saldo estado de cuenta:</b></div>
    <div style="width: 84%; height: 30px; float: left;">
        <input type="text" name="txtConciliacionSaldoI" value="<?php print $arrConciliacion["SALDO_I"]; ?>" style="text-align: right;">
        <input type="hidden" name="hdnConciliacionEstado" value="<?php print $arrConciliacion["ESTADO"]; ?>" style="text-align: right;">
    </div>
    <div style="width: 100%; height: 30px; float: left; text-align: center;">
        <button type="button" id="btnConciliacionGrabar">Guardar</button>
        <?php
        if( $ID > 0 ) {
            ?>
            <button type="button" id="btnConciliacionCerrar">Cerrar</button>
            <?php
        }
        ?>
        <script type="text/javascript" language="javascript">
        $("#btnConciliacionGrabar").button({
            icons: {
                primary: "ui-icon-disk"
            }            
        }).click(function() {
            fntConciliacionGuardar();
        });
        $("#btnConciliacionCerrar").button({
            icons: {
                primary: "ui-icon-disk"
            }            
        }).click(function() {
            fntConciliacionCerrar();
        });
        
        <?php
        if( $arrConciliacion["SALDO_I"] == $arrConciliacion["SALDO_F"] ) {
            ?>
            //$("#btnConciliacionGrabar").button("disable");
            <?php
        }
        else {
            ?>
            $("#btnConciliacionCerrar").button("disable");
            <?php            
        }
        ?>
        </script>
    </div>
    <?php
    if( $ID > 0 ) {
        ?>
        <div style="width: 900px; height: 30px; float: left">&nbsp;</div>
        <div id="div-conciliacion-actual" style="width: 900px; height: auto; float: left">&nbsp;</div>
        <div id="div-conciliacion-circulacion" style="width: 900px; height: auto; float: left">&nbsp;</div>
        <script type="text/javascript" language="javascript">
        fntConciliacionGetActual();
        </script>
        <?php
    }
    
}
function fntConciliacionActual( $db ) {
    
    $conciliacion = getParam("conciliacion");
    $cuenta = getParam("sltConciliacionCuenta");
    $mes = getParam("sltConciliacionMes");
    $anio = getParam("sltConciliacionAnio");
    $estado = getParam("hdnConciliacionEstado");
    $fecha = fntConciliacionGetUltimoDiaMes($mes, $anio);
    $tipo = 0;
    $arrTipo = array();
    $arrTipo[1] = "Cheque";
    $arrTipo[2] = "Nota de credito";
    $arrTipo[3] = "Nota de debito";
    $boolPrint = false;
    $strQuery = "";
    if( $tipo == 0 || $tipo == 1 ) {
        $strQuery .= "(SELECT NUMERO AS NO_DOCTO, '1' AS TIPO, DATE_FORMAT( FECHA, '%d-%m-%Y') AS FECHA, NOMBRE, CONCEPTO, '0' AS DEBE, MONTO AS HABER, FK_CONCILIACION 
                     FROM   cllg_bnc_cheque 
                     WHERE  FK_CUENTA = '{$cuenta}'
                     AND    FECHA <= '{$fecha}' 
                     AND    ( FK_CONCILIACION IS NULL OR FK_CONCILIACION = '{$conciliacion}' ) 
                     AND    ESTADO = '1') ";
        
    }
    if( $tipo == 0 || $tipo == 2 ) {
        $strQuery .= (!empty($strQuery)) ? "UNION ALL" : "";
        $strQuery .= "(SELECT ID AS NO_DOCTO, '2' AS TIPO, DATE_FORMAT( FECHA, '%d-%m-%Y') AS FECHA, '' AS NOMBRE, CONCEPTO, MONTO AS DEBE, '0' AS HABER, FK_CONCILIACION 
                     FROM   cllg_bnc_notas 
                     WHERE  FK_CUENTA = '{$cuenta}'
                     AND    FECHA <= '{$fecha}'  
                     AND    (  FK_CONCILIACION IS NULL OR FK_CONCILIACION = '{$conciliacion}' )  
                     AND    TIPO = '1'
                     AND    ESTADO = '1') ";
        
    }
    if( $tipo == 0 || $tipo == 3 ) {
        $strQuery .= (!empty($strQuery)) ? "UNION ALL" : "";
        $strQuery .= "(SELECT ID AS NO_DOCTO, '3' AS TIPO, DATE_FORMAT( FECHA, '%d-%m-%Y') AS FECHA, '' AS NOMBRE, CONCEPTO, '0' AS DEBE, MONTO AS HABER, FK_CONCILIACION
                     FROM   cllg_bnc_notas 
                     WHERE  FK_CUENTA = '{$cuenta}'
                     AND    FECHA <= '{$fecha}' 
                     AND    ( FK_CONCILIACION IS NULL OR FK_CONCILIACION = '{$conciliacion}' ) 
                     AND    TIPO = '2'
                     AND    ESTADO = '1') ";
    }
    $strQuery .= " ORDER BY FECHA";                 
    
    $qTMP = $db->query($strQuery);
    $intNumRows = $db->num_rows;
    if( $boolPrint ) {
        ?>
        <table width="100%" cellpadding="2" cellspacing="2" border="0">
            <tr>
                <td align="center" style="font-size: 18px; font-weight: bold;">Movimiento Bancario</td>
            </tr>
            <tr>
                <td align="center" style="font-size: 14px; font-weight: bold;"><?php print $cuenta; ?></td>
            </tr>
            <tr>
                <td align="center" style="font-size: 14px; font-weight: bold;">Del <?php print getParam("txtMovimientoFechaI"); ?> Al <?php print getParam("txtMovimientoFechaF"); ?></td>
            </tr>
            <tr>
                <td align="center">&nbsp;</td>
            </tr>
        </table>
        <?php
    }
    ?>
    <table width="100%" cellpadding="2" cellspacing="2" border="0">
        <tr>
            <td width="5%" style="border-bottom: 1px solid black;" align="center">&nbsp;</td>
            <td width="20%" style="border-bottom: 1px solid black;" align="center"><b>No. docto</b></td>
            <td width="15%" style="border-bottom: 1px solid black;" align="center"><b>Tipo documento</b></td>
            <td width="10%" style="border-bottom: 1px solid black;" align="center"><b>Fecha</b></td>
            <td width="20%" style="border-bottom: 1px solid black;" align="center"><b>Nombre</b></td>
            <td width="15%" style="border-bottom: 1px solid black;" align="center"><b>Debe</b></td>
            <td width="15%" style="border-bottom: 1px solid black;" align="center"><b>Haber</b></td>
        </tr>
    <?php
    $sinTotalConciliado = 0;
    $sinDebe = 0;
    $sinHaber = 0;
    $sinSubTotalConciliado = 0;
    $arrCuentas = array();
    if( $intNumRows > 0 ) {
        
        while ( $rTMP = $db->fetch_array($qTMP) ) {
            
            if( $rTMP["FK_CONCILIACION"] > 0 ) {
                $sinDebe += $rTMP["DEBE"];     
                $sinHaber += $rTMP["HABER"];     
            }
            ?>
            <tr>
                <td align="center">
                    <input type="checkbox" <?php print ( $estado == 2 ) ? "disabled" : ""; ?> name="chkMovimiento_<?php print $cuenta; ?>_<?php print $rTMP["TIPO"]; ?>_<?php print $rTMP["NO_DOCTO"]; ?>" value="1" <?php print ($rTMP["FK_CONCILIACION"] > 0) ? "checked" : "";  ?>>
                </td>
                <td align="center"><?php print $rTMP["NO_DOCTO"]; ?></td>
                <td align="center"><?php print $arrTipo[$rTMP["TIPO"]]; ?></td>
                <td align="center"><?php print $rTMP["FECHA"]; ?></td>
                <td><?php print $rTMP["NOMBRE"]; ?></td>
                <td align="right"><?php print number_format($rTMP["DEBE"], 2); ?></td>
                <td align="right"><?php print number_format($rTMP["HABER"], 2); ?></td>
            </tr>
            <?php         
        }
        
    }
    $sinSubTotalConciliado = $sinDebe - $sinHaber;
    ?>
    <tr>
        <td colspan="5" align="right"><b>TOTAL</b>&nbsp;</td>
        <td align="right" style="border-top: 1px solid black;"><?php print number_format($sinDebe, 2); ?></td>
        <td align="right" style="border-top: 1px solid black;"><?php print number_format($sinHaber, 2); ?></td>
    </tr>
    <tr>
        <td colspan="4">&nbsp;</td>
        <td colspan="2" align="right"><b>SUBTOTAL CONCILIADO</b>&nbsp;</td>
        <td align="right"><b><?php print number_format($sinSubTotalConciliado, 2); ?></b></td>
    </tr>
    </table>
    <?php
    $db->free_result($qTMP);
    ?>
    <br>
    <br>
    <div style="width: 100%; height: 30px;"><b>DOCUMENTOS EN CIRCULACION:</b></div>
    <?php
    $strQuery = "";
    if( $tipo == 0 || $tipo == 1 ) {
        $strQuery .= "(SELECT NUMERO AS NO_DOCTO, '1' AS TIPO, DATE_FORMAT( FECHA, '%d-%m-%Y') AS FECHA, NOMBRE, CONCEPTO, '0' AS DEBE, MONTO AS HABER, FK_CONCILIACION 
                     FROM   cllg_bnc_cheque 
                     WHERE  FK_CUENTA = '{$cuenta}' 
                     AND    FECHA <= '{$fecha}'
                     AND    ESTADO = '1'
                     AND    FK_CONCILIACION IS NULL ) ";
        
    }
    if( $tipo == 0 || $tipo == 2 ) {
        $strQuery .= (!empty($strQuery)) ? "UNION ALL" : "";
        $strQuery .= "(SELECT ID AS NO_DOCTO, '2' AS TIPO, DATE_FORMAT( FECHA, '%d-%m-%Y') AS FECHA, '' AS NOMBRE, CONCEPTO, MONTO AS DEBE, '0' AS HABER, FK_CONCILIACION 
                     FROM   cllg_bnc_notas 
                     WHERE  FK_CUENTA = '{$cuenta}' 
                     AND    FECHA <= '{$fecha}' 
                     AND    TIPO = '1'
                     AND    ESTADO = '1'
                     AND    FK_CONCILIACION IS NULL ) ";
        
    }
    if( $tipo == 0 || $tipo == 3 ) {
        $strQuery .= (!empty($strQuery)) ? "UNION ALL" : "";
        $strQuery .= "(SELECT ID AS NO_DOCTO, '3' AS TIPO, DATE_FORMAT( FECHA, '%d-%m-%Y') AS FECHA, '' AS NOMBRE, CONCEPTO, '0' AS DEBE, MONTO AS HABER, FK_CONCILIACION
                     FROM   cllg_bnc_notas 
                     WHERE  FK_CUENTA = '{$cuenta}' 
                     AND    FECHA <= '{$fecha}' 
                     AND    TIPO = '2'
                     AND    ESTADO = '1'
                     AND    FK_CONCILIACION IS NULL ) ";
    }
    $strQuery .= " ORDER BY FECHA";                 
    
    $qTMP = $db->query($strQuery);
    $intNumRows = $db->num_rows;

    ?>
    <table width="100%" cellpadding="2" cellspacing="2" border="0">
        <tr>
            <td width="5%" style="border-bottom: 1px solid black;" align="center">&nbsp;</td>
            <td width="20%" style="border-bottom: 1px solid black;" align="center"><b>No. docto</b></td>
            <td width="15%" style="border-bottom: 1px solid black;" align="center"><b>Tipo documento</b></td>
            <td width="10%" style="border-bottom: 1px solid black;" align="center"><b>Fecha</b></td>
            <td width="20%" style="border-bottom: 1px solid black;" align="center"><b>Nombre</b></td>
            <td width="15%" style="border-bottom: 1px solid black;" align="center"><b>Debe</b></td>
            <td width="15%" style="border-bottom: 1px solid black;" align="center"><b>Haber</b></td>
        </tr>
    <?php
    $sinDebe = 0;
    $sinHaber = 0;
    $sinSubTotalCirculacion = 0;
    $arrCuentas = array();
    if( $intNumRows > 0 ) {
        
        while ( $rTMP = $db->fetch_array($qTMP) ) {
            
            $sinDebe += $rTMP["DEBE"];     
            $sinHaber += $rTMP["HABER"];     
            ?>
            <tr>
                <td align="center">
                    &nbsp;
                </td>
                <td align="center"><?php print $rTMP["NO_DOCTO"]; ?></td>
                <td align="center"><?php print $arrTipo[$rTMP["TIPO"]]; ?></td>
                <td align="center"><?php print $rTMP["FECHA"]; ?></td>
                <td><?php print $rTMP["NOMBRE"]; ?></td>
                <td align="right"><?php print number_format($rTMP["DEBE"], 2); ?></td>
                <td align="right"><?php print number_format($rTMP["HABER"], 2); ?></td>
            </tr>
            <?php         
        }
        
    }
    
    $sinSubTotalCirculacion = $sinDebe - $sinHaber;
    if( $sinSubTotalCirculacion >= 0 ) {
        $sinTotalConciliado = $sinSubTotalConciliado - $sinSubTotalCirculacion;
    }
    if( $sinSubTotalCirculacion < 0 ) {
        $sinTotalConciliado = $sinSubTotalConciliado - $sinSubTotalCirculacion;
    }
    ?>
    <input type="hidden" name="txtConciliacionSaldoF" value="<?php print $sinTotalConciliado; ?>">
    <tr>
        <td colspan="5" align="right"><b>TOTAL</b>&nbsp;</td>
        <td align="right" style="border-top: 1px solid black;"><?php print number_format($sinDebe, 2); ?></td>
        <td align="right" style="border-top: 1px solid black;"><?php print number_format($sinHaber, 2); ?></td>
    </tr>
    <tr>
        <td colspan="4">&nbsp;</td>
        <td colspan="2" align="right"><b>SUBTOTAL CIRCULACION</b>&nbsp;</td>
        <td align="right"><b><?php print number_format($sinSubTotalCirculacion, 2); ?></b></td>
    </tr>
    <tr>
        <td colspan="4">&nbsp;</td>
        <td colspan="2" align="right"><b>TOTAL CONCILIADO</b></td>
        <td align="right"><b><?php print number_format($sinTotalConciliado, 2); ?></b></td>
    </tr>
    </table>
    <script type="text/javascript" language="javascript">
    $( function(){
        sinConciliacionSaldoI = $("input[name='txtConciliacionSaldoI']").val();
        sinConciliacionSaldoF = $("input[name='txtConciliacionSaldoF']").val();
        if( sinConciliacionSaldoI == sinConciliacionSaldoF ) {
            
        }
        
    });
    </script>
    <?php
    $db->free_result($qTMP);
    
}
function fntConciliacionGuardar( $db ) {
    
    $cuenta = getParam("sltConciliacionCuenta");
    $conciliacion = getParam("sltConciliacionConciliacion");
    $mes = getParam("sltConciliacionMes");
    $anio = getParam("sltConciliacionAnio");
    $fecha = fntConciliacionGetUltimoDiaMes($mes, $anio);
    $saldo_i = getParam("txtConciliacionSaldoI");
    $saldo_f = getParam("txtConciliacionSaldoF");
    
    if( $conciliacion == 0 ) { 
        $db->query("INSERT INTO cllg_bnc_conciliacion ( FK_CUENTA, FECHA, SALDO_I, SALDO_F, ESTADO ) VALUES ( '{$cuenta}', '{$fecha}', '{$saldo_i}', '{$saldo_f}', '1')");
        $conciliacion = mysql_insert_id ( $db->link_id );
    }
    else {
        $db->query("UPDATE cllg_bnc_conciliacion SET SALDO_I = '{$saldo_i}', SALDO_F = '{$saldo_f}' WHERE ID = '{$conciliacion}'");
        $db->query("UPDATE cllg_bnc_cheque SET FK_CONCILIACION = NULL WHERE FK_CONCILIACION = '{$conciliacion}'");
        $db->query("UPDATE cllg_bnc_notas SET FK_CONCILIACION = NULL WHERE FK_CONCILIACION = '{$conciliacion}'");
        while( $arrPost = each($_POST) ) {
            
            $arrExplode = explode( "_", $arrPost["key"]);
            if( $arrExplode[0] == "chkMovimiento" ) {
                
                if( $arrExplode[2] == 1 ) {
                    $db->query("UPDATE cllg_bnc_cheque SET FK_CONCILIACION = '{$conciliacion}'  WHERE FK_CUENTA = '{$arrExplode[1]}' AND NUMERO = '{$arrExplode[3]}'");    
                }
                if( $arrExplode[2] == 2 ) {
                    $db->query("UPDATE cllg_bnc_notas SET FK_CONCILIACION = '{$conciliacion}' WHERE FK_CUENTA = '{$arrExplode[1]}' AND TIPO = '1' AND ID = '{$arrExplode[3]}'");
                }
                if( $arrExplode[2] == 3 ) {
                    $db->query("UPDATE cllg_bnc_notas SET FK_CONCILIACION = '{$conciliacion}' WHERE FK_CUENTA = '{$arrExplode[1]}' AND TIPO = '2' AND ID = '{$arrExplode[3]}'");
                }
                
            }
        }
        
        
    }
    ?>
    <script type="text/javascript" language="javascript">
    fntConciliacionGetConciliaciones('<?php print $conciliacion; ?>');
    </script>
    <?php
    
}
function fntConciliacionCerrar( $db ) {
    
    $conciliacion = getParam("sltConciliacionConciliacion");
    
    $db->query("UPDATE cllg_bnc_conciliacion SET ESTADO = '2' WHERE ID = '{$conciliacion}'");
    ?>
    <script type="text/javascript" language="javascript">
    fntConciliacionGetConciliaciones('<?php print $conciliacion; ?>');
    </script>
    <?php
    
}
function fntConciliacionGetUltimoDiaMes($mes,$anio) {
    $fecha = "";
    for ($dia=28;$dia<=31;$dia++) {
        if(checkdate($mes,$dia,$anio)) 
            $fecha="$anio-$mes-$dia";
    }
    return $fecha;

}
?>